import { businessAdd, businessInfo, businessUpdate } from "@/services/chargingManage";
import { getUuid } from "@/utils/utils";
import { Button, Checkbox, Col, Divider, Drawer, Form, Icon, Input, message, Modal, Radio, Row, Tabs, Upload } from "antd";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import ManageList from "./manageList";

class BusinessModal extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      id:null,
      imgList:[],
      relationList:[],
      activeKey:'info'
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initModal = id => {
    this.setState({
      visible:true,
      id
    },() => {
      if(id){
        this.getDetail()
      }
    })
  }

  getDetail = async () => {
    const res = await businessInfo({id:this.state.id})
    let obj = {}
    let fields = [
      "name",
      // "locationType",
      "useTypes",
      "unifiedSocialCreditCode",
      "dengbaishiCode",
      "address",
      "userName",
      "userPhone",
      "userMail",
      "safeType",
      "safeMail",
      "safePhone"
    ]
    for(const item of fields){
      obj[item] = res[item]
    }
    this.props.form.setFieldsValue(obj)
    this.setState({imgList:res.certs,relationList:res.relations})

  }

  onClose = () => {
    this.props.form.resetFields()
    this.setState({
      visible:false,
      id:null,
      imgList:[],
      relationList:[]
    })
  }

  okValidate = () => {
    if(this.state.activeKey === 'info'){
      this.props.form.validateFields((error,values) => {
        if(!error){
          const { relationList,imgList } = this.state
          values.relations = relationList
          values.certs = imgList
          this.doSave(values)
        }
      })
    }
  }

  doSave = async values => {
    let res = {}
    if(this.state.id){
      values.id = this.state.id
      res = await businessUpdate(values)
      if(res.code === -1){return false}
      message.info(res.message)
      this.onClose()
      this.props.refreshList()
    }else{
      res = await businessAdd(values)
      if(res.code === -1){return false}
      this.setState({
        id:res.data
      })
      message.info(res.message)
      this.props.refreshList()
    }
    
  }

    /**
   * 上传图片前判断
   * @returns {*}
   */
    beforeUpload = file => {
      let b = /\.(png|jpg|gif)$/;
      let a = file.name.toLowerCase();
  
      const pig = b.test(a);
      const isJPG = file.type;
      const isLt2M = file.size / 1024 / 1024 < 2;
  
      if (!pig) {
        if (!isLt2M) {
          message.error('请上传小于2M的图片');
        } else {
          message.error('请上传图片格式');
        }
      } else {
        if (!isLt2M) {
          message.error('请上传小于2M的图片');
        }
      }
      return isJPG && isLt2M && pig;
    };

      /**
   * 更换图片
   * @returns {*}
   */
  handleChangeImage = (info, type) => {
    if (info.file.status === 'done') {
      const { imgList } = this.state;
      imgList.push({imgUrl:info.file.response.url})
      this.setState({imgList})
    }
  };

  removeImg = item => {
    const { imgList } = this.state;
    const newList = imgList.filter(img => img.imgUrl != item)
    this.setState({imgList:newList})
  }

  addRelationList = () => {
    const { relationList } = this.state;
    relationList.push({
      id:getUuid(),
      relEnterprise:"",
      uniqueId:"",
      relType:"",
      rel:"",
      userName:"",
      userPhone:"",
      address:""
    })
    this.setState({relationList})
  }

  changeValue = (value,index,field) => {
    const { relationList } = this.state;
    relationList[index][field] = value;
    this.setState({relationList})
  }

  removeRelation = id => {
    const { relationList } = this.state;
    const newList = relationList.filter(item => item.id != id)
    this.setState({relationList:newList})

  }

  checkField(rule, value, callback) {
    const reg = /^1[0-9]\d{9}$/;
    if (rule.field === 'safePhone') {
      if (value) {
        if (reg.test(value)) {
          callback();
        } else {
          callback(formatMessage({ id: 'chargingManage.businessManage.businessModal.inputPhone' }));
        }
      } else {
        callback();
      }
    }
  }

  render(){
    const { visible,id,imgList,relationList,activeKey } = this.state
    const { form:{getFieldDecorator,getFieldValue} } = this.props;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
    };

    return (
      <Drawer
        visible={visible}
        onClose={this.onClose}
        width={'100%'}
      >
        <Tabs activeKey={activeKey} onChange={activeKey => this.setState({activeKey})}>
          <Tabs.TabPane tab={formatMessage({ id: 'chargingManage.businessManage.businessModal.infoTab' })} key="info">
            <Form {...formItemLayout} className="normalForm" style={{marginBottom:64}}>
              <Row>
                <Col span={12}>
                  <strong>{formatMessage({ id: 'chargingManage.businessManage.businessModal.basicInfo' })}</strong>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.companyName' })}>
                    {getFieldDecorator("name",{rules:[{required:true,message:"请输入"}]})(
                      <Input placeholder={formatMessage({ id: 'chargingManage.businessManage.businessModal.companyNamePlaceholder' })} />
                    )}
                  </Form.Item>
                  {/**
                    <Form.Item label="平台定位">
                    {getFieldDecorator("locationType",{rules:[{required:true,message:"请输入"}]})(
                      <Radio.Group>
                        <Radio value={0}>所有方</Radio>
                        <Radio value={1}>服务方</Radio>
                        <Radio value={2}>用户方</Radio>
                      </Radio.Group>
                    )}
                  </Form.Item> */}
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.useLocation' })}>
                    {getFieldDecorator("useTypes",{rules:[{required:true,message:"请输入"}]})(
                      <Checkbox.Group>
                        <Checkbox value={'0'}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.signingParty' })}</Checkbox>
                        <Checkbox value={'1'}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.usingParty' })}</Checkbox>
                        <Checkbox value={'2'}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.settlementParty' })}</Checkbox>
                      </Checkbox.Group>
                    )}
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <strong>{formatMessage({ id: 'chargingManage.businessManage.businessModal.companyInfo' })}</strong>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.creditCode' })}>
                    {getFieldDecorator("unifiedSocialCreditCode")(
                      <Input placeholder={formatMessage({ id: 'chargingManage.businessManage.businessModal.creditCodePlaceholder' })} />
                    )}
                  </Form.Item>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.dunAndBradstreetCode' })}>
                    {getFieldDecorator("dengbaishiCode")(
                      <Input placeholder={formatMessage({ id: 'chargingManage.businessManage.businessModal.dunAndBradstreetCodePlaceholder' })} />
                    )}
                  </Form.Item>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.address' })}>
                    {getFieldDecorator("address")(
                      <Input placeholder={formatMessage({ id: 'chargingManage.businessManage.businessModal.addressPlaceholder' })} />
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <strong>{formatMessage({ id: 'chargingManage.businessManage.businessModal.companyAccount' })}</strong>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.adminName' })}>
                    {getFieldDecorator("userName")(
                      <Input />
                    )}
                  </Form.Item>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.contactPhone' })}>
                    {getFieldDecorator("userPhone")(
                      <Input />
                    )}
                  </Form.Item>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.billEmail' })}>
                    {getFieldDecorator("userMail")(
                      <Input />
                    )}
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <strong>{formatMessage({ id: 'chargingManage.businessManage.businessModal.changeManagement' })}</strong>
                  <Form.Item label={formatMessage({ id: 'businessReadonly.verificationMethod' })} colon={false}>
                    {getFieldDecorator("safeType",{initialValue:0})(
                      <Radio.Group>
                        <Radio value={0}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.safeEmail' })}</Radio>
                        <Radio value={1}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.companyAuthorization' })}</Radio>
                      </Radio.Group>
                    )}
                  </Form.Item>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.safeEmailLabel' })}>
                    {getFieldDecorator("safeMail")(
                      <Input placeholder={formatMessage({ id: 'chargingManage.businessManage.businessModal.safeEmailPlaceholder' })} />
                    )}
                  </Form.Item>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.authPhone' })}>
                    {getFieldDecorator("safePhone",{rules:[{ validator: this.checkField, }]})(
                      <Input placeholder={formatMessage({ id: 'chargingManage.businessManage.businessModal.authPhonePlaceholder' })} maxLength={11} />
                    )}
                  </Form.Item>
                  <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.authorizationDocument' })}>
                    <Upload
                      name="file"
                      listType="picture"
                      className="avatar-uploader"
                      showUploadList={false}
                      action="/cloud/file/upload"
                      beforeUpload={this.beforeUpload}
                      onChange={info => this.handleChangeImage(info, 'winLogo')}
                      accept=".png,.jpg"
                    >
                      <Button>{formatMessage({ id: 'chargingManage.businessManage.businessModal.authorizationDocumentButton' })}</Button>
                    </Upload>
                    <div style={{display:"flex",marginTop:10,flexWrap:"wrap",gap:"10px"}}>
                      {
                        imgList.map(item => {
                          return (
                            <div key={item.imgUrl}>
                              <img src={item.imgUrl} style={{width:80,height:40,marginBottom:10}} />
                              <div style={{textAlign:"center"}}>
                                <a href={item.imgUrl} target="_blank" style={{marginRight:8}}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.view' })}</a>
                                <Button type="link" size="small" onClick={() => this.removeImg(item.imgUrl)} style={{color:"red"}}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.delete' })}</Button>
                              </div>
                            </div>
                          )
                        })
                      }
                    </div>
                  </Form.Item>
                </Col>
              </Row>

              <Divider style={{marginTop:0}} />

              <Row>
                <Col span={24}>
                  <div style={{marginBottom:10}}>
                    <strong>{formatMessage({ id: 'chargingManage.businessManage.businessModal.relationshipGraph' })}</strong>
                    <Button type="primary" style={{marginLeft:10}} onClick={this.addRelationList}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.newCompanyRelation' })}</Button>
                  </div>
                  {
                    relationList.map((item,index) => {
                      return (
                        <Row style={{borderBottom:"1px solid #e8e8e8",marginBottom:24}} key={item.id}>
                          <Col span={6}>
                            <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.relatedCompany' })} labelCol={{span:6}}>
                              <Input value={item.relEnterprise} onChange={e => this.changeValue(e.target.value,index,'relEnterprise')} />
                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.uniqueId' })} labelCol={{span:6}}>
                              <Input value={item.uniqueId} onChange={e => this.changeValue(e.target.value,index,'uniqueId')} />
                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.relationType' })} labelCol={{span:6}}>
                              <Input value={item.relType} onChange={e => this.changeValue(e.target.value,index,'relType')} placeholder={formatMessage({ id: 'chargingManage.businessManage.businessModal.relationTypePlaceholder' })} />
                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.relation' })} labelCol={{span:6}}>
                              <Input value={item.rel} onChange={e => this.changeValue(e.target.value,index,'rel')} placeholder={formatMessage({ id: 'chargingManage.businessManage.businessModal.relationPlaceholder' })} />
                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.contactPerson' })} labelCol={{span:6}}>
                              <Input value={item.userName} onChange={e => this.changeValue(e.target.value,index,'userName')} />
                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.contactPhone2' })} labelCol={{span:6}}>
                              <Input value={item.userPhone} onChange={e => this.changeValue(e.target.value,index,'userPhone')} />
                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item label={formatMessage({ id: 'chargingManage.businessManage.businessModal.address2' })} labelCol={{span:6}}>
                              <Input value={item.address} onChange={e => this.changeValue(e.target.value,index,'address')} />
                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item label="" labelCol={{span:6}}>
                              <Icon type="delete" style={{cursor:"pointer"}} onClick={() => this.removeRelation(item.id)} />
                            </Form.Item>
                          </Col>
                        </Row>
                      )
                    })
                  }
                </Col>
              </Row>

            </Form>
          </Tabs.TabPane>
          <Tabs.TabPane tab={formatMessage({ id: 'chargingManage.businessManage.businessModal.contractTab' })} key="contract" disabled={!id}>
            {
              activeKey === 'contract' ? <ManageList type='contract' enterpriseId={id} /> : ''
            }
          </Tabs.TabPane>
          <Tabs.TabPane tab={formatMessage({ id: 'chargingManage.businessManage.businessModal.projectTab' })} key="project" disabled={!id}>
            {
              activeKey === 'project' ? <ManageList type='project' enterpriseId={id} /> : ''
            }
          </Tabs.TabPane>
        </Tabs>

        {
          activeKey === 'info' ? (
            <div
              style={{
                position: 'absolute',
                right: 0,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                padding: '10px 16px',
                background: '#fff',
                textAlign: 'right',
              }}
            >
              <Button onClick={this.onClose} style={{ marginRight: 8 }}>{formatMessage({ id: 'chargingManage.businessManage.businessModal.cancel' })}</Button>
              <Button onClick={this.okValidate} type="primary">{formatMessage({ id: 'chargingManage.businessManage.businessModal.save' })}</Button>
            </div>
          ) : ''
        }
      </Drawer>
    )
  }
}

export default Form.create()(BusinessModal)